/**
 * Independent time operation tool to facilitate subsequent switch to dayjs
 */
import dayjs from 'dayjs';

const DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss';
const DATE_FORMAT = 'YYYY-MM-DD';

export function formatToDateTime(date?: dayjs.ConfigType, format = DATE_TIME_FORMAT): string {
  return dayjs(date).format(format);
}

export function formatToDate(date?: dayjs.ConfigType, format = DATE_FORMAT): string {
  return dayjs(date).format(format);
}

export function isBetween(date, start, end, unit = 'millisecond', inclusivity = '()') {
  const target = new Date(date);
  const startDate = new Date(start);
  const endDate = new Date(end);

  // 转换为毫秒值
  const targetTime = target.getTime();
  const startTime = startDate.getTime();
  const endTime = endDate.getTime();

  // 根据不同的时间单位计算差值
  let diffStart, diffEnd;
  switch (unit) {
    case 'day':
      diffStart = Math.floor((targetTime - startTime) / (1000 * 60 * 60 * 24));
      diffEnd = Math.floor((endTime - targetTime) / (1000 * 60 * 60 * 24));
      break;
    case 'month':
      const targetYear = target.getFullYear();
      const targetMonth = target.getMonth();
      const startYear = startDate.getFullYear();
      const startMonth = startDate.getMonth();
      const endYear = endDate.getFullYear();
      const endMonth = endDate.getMonth();
      diffStart = (targetYear - startYear) * 12 + (targetMonth - startMonth);
      diffEnd = (endYear - targetYear) * 12 + (endMonth - targetMonth);
      break;
    case 'year':
      diffStart = target.getFullYear() - startDate.getFullYear();
      diffEnd = endDate.getFullYear() - target.getFullYear();
      break;
    default:
      diffStart = targetTime - startTime;
      diffEnd = endTime - targetTime;
  }

  // 根据边界包含情况判断
  if (inclusivity === '()') {
    return diffStart > 0 && diffEnd > 0;
  } else if (inclusivity === '[]') {
    return diffStart >= 0 && diffEnd >= 0;
  } else if (inclusivity === '(]') {
    return diffStart > 0 && diffEnd >= 0;
  } else if (inclusivity === '[)') {
    return diffStart >= 0 && diffEnd > 0;
  }
  return false;
}
export const dateUtil = dayjs;
